package com.qfedu.fmmall.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.fmmall.config.ExceptionR;
import com.qfedu.fmmall.entity.*;
import com.qfedu.fmmall.mapper.OrderItemMapper;
import com.qfedu.fmmall.mapper.OrdersMapper;
import com.qfedu.fmmall.mapper.ProductSkuMapper;
import com.qfedu.fmmall.mapper.ShoppingCartMapper;
import com.qfedu.fmmall.service.OrdersService;
import com.qfedu.fmmall.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 订单  服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Resource
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private ProductSkuMapper productSkuMapper;
    /**
     * 用户提交订单接口
     * @return
     */
    @Transactional
    public ResultVO add(String cids,Orders order) throws ExceptionR {
        String []ids=cids.split(",");
        List<Integer> listIds =new ArrayList<>();
        for (String id: ids) {
            listIds.add(Integer.parseInt(id));
        }
        String untiled="";
        String uuid="";
        boolean flag = false;
        List<ShoppingCartVO> list = shoppingCartMapper.selectScart(listIds);
        for (ShoppingCartVO item: list) {
            if ((item.getSkuStock()<Integer.parseInt(item.getCartNum()))){
                throw new ExceptionR(item.getSkuName()+"库存不足，添加失败");
            }else {
                if (list.get(list.size() - 1).equals(item)) {
                    untiled = untiled + item.getProductName();
                    flag=true;
                } else {
                    untiled = untiled + item.getProductName() + ",";
                }
                /**
                 * 添加订单
                 */
                if (flag){
                    order.setUntitled(untiled);
                    order.setStatus("1");
                    uuid = UUID.randomUUID().toString().replace("-", "");
                    order.setOrderId(uuid);
                    order.setCreateTime(new Date());
                    order.setUpdateTime(new Date());
                      ordersMapper.insert(order);
                     flag = false;
                    }
                        //生产商品快照
//                        List<OrderItem> orders = new ArrayList<OrderItem>();
                            Integer carNum= Integer.parseInt(item.getCartNum());
                            OrderItem orderItem = new OrderItem();
                            String itemId=System.currentTimeMillis()+""+new Random().nextInt(9999)+10000;
                            orderItem.setItemId(itemId);
                            orderItem.setOrderId(uuid);
                            orderItem.setProductId(item.getProductId());
                            orderItem.setProductName(item.getProductName());
                            orderItem.setProductImg(item.getProductImg());
                            orderItem.setSkuId(item.getSkuId());
                            orderItem.setSkuName(item.getSkuName());
                            orderItem.setProductPrice(item.getProductPrice());
                            orderItem.setBuyCounts(carNum);
                            orderItem.setTotalAmount(new BigDecimal(item.getSellPrice()*carNum));
                            orderItem.setBasketDate(new Date());
                            orderItem.setBuyTime(new Date());
                            orderItem.setIsComment(0);
//                            orders.add(orderItem);
                        Integer insertList = orderItemMapper.insert(orderItem);
                        if (insertList>0){
                                ProductSku productSku = productSkuMapper.selectById(item.getSkuId());
                                productSku.setStock(item.getSkuStock()-Integer.parseInt(item.getCartNum()));
                                productSku.setUpdateTime(new Date());
                                productSkuMapper.updateById(productSku);
                            for (Integer items: listIds) {
                                 shoppingCartMapper.deleteById(items);
                            }
                        }else {
                           throw  new ExceptionR("添加订单快照失败");

                        }
                }
        }
        return ResultVO.success(order,"订单添加成功！");
    }

    public ResultVO getOrdersStatus(String orderId){
        Orders orders = ordersMapper.selectById(orderId);
        return ResultVO.success(orders.getStatus(),"success");
    }
}
